/*
Copyright (c) 2009 Hayden Curran <haydenz@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
        this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
        this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
    * The names of its contributors may not be used to endorse or promote
        products derived from this software without specific prior
        written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "rcon.h"

/*
    Initialises rcon_status_t
*/
int rcon_init(rcon_status_t *rcon) {
    rcon->buffer = malloc(sizeof(rcon->buffer));
    rcon->buffer->size = 0;
    rcon->buffer->string1[0] = 0;

    rcon->request_id = 0;
    rcon->authenticated = 0;

    return 1;
}

/*
    Connects to GAME_SERVER:GAME_PORT and returns the file descriptor
    On error returns -1.
*/
int rcon_connect() {
    struct addrinfo hints, *res;
    int rconfd, ret;

    // first, load up address structs with getaddrinfo():
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    getaddrinfo(GAME_SERVER, GAME_PORT, &hints, &res);

    // make a socket:
    rconfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);

    // connect!
    ret = connect(rconfd, res->ai_addr, res->ai_addrlen);
    freeaddrinfo(res);
    if (ret == -1) {
        perror("rcon connect");
        return -1;
    }

    return rconfd;
}

/*
    Authenticates to the server using RCON_PASSWORD
*/
int rcon_authenticate(rcon_status_t *rcon) {
    rcon_send(rcon, SERVERDATA_AUTH, RCON_PASSWORD, "");
    return 1;
}

/*
    Sends stuff to rcon
    Returns the length of the data sent
    On error returns -1.
*/
int rcon_send(rcon_status_t *rcon, int command, char *string1, char *string2) {
    int ret, size;

    rcon->request_id++;
    size = 10 + strlen(string1) + strlen(string2);

    // TODO: use htonl() on these ints

    ret = send(rcon->rconfd, (void *)&size, sizeof(int), 0);
    if (ret == -1) {
        perror("rcon send");
        return -1;
    }
    ret = send(rcon->rconfd, (void *)&(rcon->request_id), sizeof(int), 0);
    if (ret == -1) {
        perror("rcon send");
        return -1;
    }
    ret = send(rcon->rconfd, (void *)&command, sizeof(int), 0);
    if (ret == -1) {
        perror("rcon send");
        return -1;
    }
    ret = send(rcon->rconfd, string1, strlen(string1) + 1, 0);
    if (ret == -1) {
        perror("rcon send");
        return -1;
    }
    ret = send(rcon->rconfd, string2, strlen(string2) + 1,0);
    if (ret == -1) {
        perror("rcon send");
        return -1;
    }

    return size;
}

/*
    Receives from rcon then processes it
    Returns the length of the buffer
    On error returns -1.
*/
int rcon_receive(rcon_status_t *rcon) {
    int ret, len;
    char buf[RCON_STRING_LENGTH * 2];

    if (rcon->buffer->size == 0) {
        // TODO: use ntohl() on these ints

        ret = recv(rcon->rconfd, (void *)&rcon->buffer->size, sizeof(int), 0);
        if (ret == -1) {
            perror("rcon recv");
            return -1;
        }
        ret = recv(rcon->rconfd, (void *)&rcon->buffer->id, sizeof(int), 0);
        if (ret == -1) {
            perror("rcon recv");
            return -1;
        }
        ret = recv(rcon->rconfd, (void *)&rcon->buffer->response, sizeof(int), 0);
        if (ret == -1) {
            perror("rcon recv");
            return -1;
        }
    }
    len = strlen(rcon->buffer->string1);

    ret = recv(rcon->rconfd, buf, rcon->buffer->size - 8 - len, 0);
    if (ret == -1) {
        perror("rcon recv");
        return -1;
    }
    buf[ret] = 0;

    strncpy((rcon->buffer->string1 + len), buf, RCON_STRING_LENGTH - 1);

    len = 10 + strlen(rcon->buffer->string1);

    if (len == rcon->buffer->size) {
        len = rcon->buffer->size;
        rcon->buffer->size = 0;

        return rcon_parse_buffer(rcon);
    }

    return len;
}

/*
    Parses the rcon->buffer data
    On error returns -1.
*/
int rcon_parse_buffer(rcon_status_t *rcon) {
    switch(rcon->buffer->response) {
        case SERVERDATA_AUTH_RESPONSE:
            switch(rcon->buffer->id) {
                case 1:
                    rcon->authenticated = 1;
                    printf("RCON authenticated.\n");
                    // TODO: automatically detect IP
                    rcon_send(rcon, SERVERDATA_EXECCOMMAND,
                        "logaddress_del 118.90.126.79:6112", "");
                    rcon_send(rcon, SERVERDATA_EXECCOMMAND,
                        "mp_loglevel 3", "");
                    break;
                case -1:
                    printf("RCON Password Refused\n");
                    return -1;
                default:
                    printf("RCON Bad Auth Response ID = %d\n",
                        rcon->buffer->id);
                    return -1;
            };
            break;
        case SERVERDATA_RESPONSE_VALUE:
            if (rcon->buffer->size > 10)
                printf("%s", rcon->buffer->string1);
            break;
        default:
            printf("RCON Unexpected response: %d\n", rcon->buffer->response);
            break;
    };

    return 1;
}
